<template>
  <div class="flex justify-center" v-loading.fullscreen.lock="loading">
    <div class="demo-image__lazy" @scroll="handleScroll" style="width: 50%">
      <el-image v-for="url in imageUrls" :key="url" :src="url" lazy/>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {getQueryParam} from '@/utils'
import {post} from '@/utils/request'

const imageUrls = ref([])
const loading = ref(false)
const range = {min: 0, max: 10000}
const getImage = (pageIndex) => {
  const param = {}
  param.doc_id = getQueryParam('doc_id')
  param.page_index = pageIndex
  loading.value = true
  post('/retrieve/get_target_page', param, 'json').then(r => {
    loading.value = false
    if (pageIndex >= getQueryParam('page_index')) {
      imageUrls.value.push('data:image/png;base64,' + r.page_img)
    } else {
      imageUrls.value.unshift('data:image/png;base64,' + r.page_img)
    }
  })
}
const handleScroll = (e) => {
  const scrollTop = e.target.scrollTop
  const scrollHeight = e.target.scrollHeight
  const offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
  const currentHeight = Math.ceil(scrollTop + offsetHeight)
  if (scrollTop == 0 && range.min > 0) {
    range.min--
    getImage(Number.parseInt(range.min))
    e.target.scrollTop = 30
  }
  if (currentHeight >= scrollHeight) {
    range.max++
    getImage(Number.parseInt(range.max))
  }
}
onMounted(() => {
  const curIndex = Number.parseInt(getQueryParam('page_index'))
  range.min = (curIndex - 1 > 0) ? (curIndex - 1) : 1
  range.max = curIndex + 1
  getImage(range.min)
  getImage(curIndex)
  getImage(range.max)
})
</script>

<style scoped>
.demo-image__lazy {
  height: 800px;
  overflow-y: auto;
}

.demo-image__lazy .el-image {
  display: block;
  min-height: 100px;
  margin-bottom: 10px;
}

.demo-image__lazy .el-image:last-child {
  margin-bottom: 0;
}
</style>
